import frappe
from frappe import _
from frappe.utils import flt, cint


@frappe.whitelist()
def split_work_order(work_order_name, qty):
    """
    支持两种模式
    1. 拆分两张订单：输入原订单保留数量，另一张为剩余数量
    2. 平均拆分多张：输入原订单数量/拆分张数，如1000/4或 /4, 共拆分成4张每张250（包括原订单）
    """

    new_orders = []
    doc = frappe.get_doc("Work Order", work_order_name)
    if "/" in qty:
        base_qty, count = qty.split('/', 1)
        base_qty = flt(base_qty) if base_qty else doc.qty
        if flt(doc.qty - base_qty, 0):
            frappe.throw(_("Base Qty {0} should be same as order qty {1}")
                .format(base_qty, doc.qty)
            )
        count = cint(count)
        order_qty =  flt(base_qty) / count

        doc1 = doc if doc.docstatus == 0 else frappe.copy_doc(doc)
        doc1.qty = order_qty
        if doc.docstatus == 1:
            doc.cancel()
            doc1.amended_from = doc.name
            doc1.submit()
        else:
            doc1.save()

        for i in range(1, count):
            new_order = frappe.copy_doc(doc)
            new_order.qty = order_qty
            new_order.save(ignore_permissions = 1)
            new_orders.append(new_order.name)
    else:
        order_qty = flt(qty)        
        if order_qty <= 0 or order_qty >= doc.qty:
            frappe.throw(_("Qty should be more than 0 and less than order qty"))

        doc2 = frappe.copy_doc(doc)
        doc2.qty = doc.qty - order_qty
          
        doc1 = doc if doc.docstatus == 0 else frappe.copy_doc(doc)
        doc1.qty = order_qty
        if doc.docstatus == 1:
            doc.cancel()
            doc1.amended_from = doc.name
            doc1.submit()
        else:
            doc1.save()

        doc2.save()
        new_orders.append(doc2.name)

    return new_orders

@frappe.whitelist()
def get_exploded_item_oem_code(bom, data = []):    
    bom_item = frappe.qb.DocType('BOM Item')

    exploded_items = frappe.qb.from_(bom_item    
        ).select(bom_item.bom_no, bom_item.item_code, bom_item.oem_code            
        ).where(bom_item.parent == bom
        ).run(as_dict=1)        

    for item in exploded_items:        
        data.append([item.item_code, item.oem_code])
        if item.bom_no:
            get_exploded_item_oem_code(item.bom_no, data)

    return  frappe._dict(data) if data else {}